package com.dq.service.record.impl;

import com.dq.exception.customException.AdminException;
import com.dq.controller.in.RestDayRecordQuery;
import com.dq.domain.org.Org;
import com.dq.domain.record.RestDayRecord;
import com.dq.repository.BaseRepositories;
import com.dq.service.record.RestDayRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author liuhui
 * @date 2019/11/23 0023 13:52:11
 */
@Service
public class RestDayRecordServiceImpl extends BaseRepositories implements RestDayRecordService {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<RestDayRecord> findByWhere(RestDayRecordQuery restDayRecordQuery, Org org)throws AdminException {
        StringBuilder hql = new StringBuilder("select u from RestDayRecord u where u.deleted=false");
        Query q = createWhereHql(restDayRecordQuery,org,hql);
        q.setFirstResult((restDayRecordQuery.getPage()-1)*restDayRecordQuery.getSize());
        q.setMaxResults(restDayRecordQuery.getSize());
        List<RestDayRecord> restDayRecordList = q.getResultList();
        return restDayRecordList;
    }


    @Override
    public Long countByWhere(RestDayRecordQuery restDayRecordQuery,Org org)throws AdminException{
        StringBuilder hql = new StringBuilder("select count(u) from RestDayRecord u where u.deleted=false");
        Query q = createWhereHql(restDayRecordQuery,org,hql);
        return new Long((long) q.getResultList().get(0));
    }

    public Query createWhereHql(RestDayRecordQuery restDayRecordQuery,Org org,StringBuilder hql)throws AdminException{
        hql.append(" and u.org =:org");
        if(restDayRecordQuery.getBeginTime() != null){
            hql.append(" and u.beginTime >=:beginTime");
        }
        if(restDayRecordQuery.getEndTime() != null){
            hql.append(" and u.beginTime <=:endTime");
        }
        if(StringUtils.isNotEmpty(restDayRecordQuery.getRestReason())){
            hql.append(" and u.reason like:reason");
        }
        hql.append(" ORDER BY u.createTime desc");
        Query query = entityManager.createQuery(hql.toString());
        query.setParameter("org",org);
        if(restDayRecordQuery.getBeginTime() != null){
            query.setParameter("beginTime",restDayRecordQuery.getBeginTime());
        }
        if(restDayRecordQuery.getEndTime() != null){
            query.setParameter("endTime",restDayRecordQuery.getEndTime());
        }
        if(StringUtils.isNotEmpty(restDayRecordQuery.getRestReason())){
            query.setParameter("reason","%"+restDayRecordQuery.getRestReason()+"%");
        }
        return query;
    }
}
